package com.guigu.qingcheng.servicegoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.qingcheng.pojo.goods.*;
import com.guigu.qingcheng.servicegoods.mapper.*;
import com.guigu.qingcheng.servicegoods.service.TbSkuService;
import com.guigu.qingcheng.servicegoods.service.TbSpuService;
import com.guigu.qingcheng.utils.IdWorker;
import com.guigu.qingcheng.utils.R;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbSpuServiceImpl extends ServiceImpl<TbSpuMapper, TbSpu> implements TbSpuService {

    @Resource
    private TbSpuMapper spuMapper;

    @Resource
    private TbSkuMapper skuMapper;

    @Resource
    private IdWorker idWorker;

    @Resource
    private TbCategoryMapper categoryMapper;

    @Resource
    private TbBrandMapper brandMapper;

    @Resource
    private TbCategoryBrandMapper categoryBrandMapper;

    @Autowired
    private TbSpuService tbSpuService;

    @Autowired
    private TbSkuService skuService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //根据条件查询封装查询对象
    public QueryWrapper<TbSpu> queryWrapper(Map<String, Object> searchMap){
        QueryWrapper<TbSpu> wapper = new QueryWrapper<TbSpu>();
        if(searchMap != null){
            if(searchMap.get("id") != null && !"".equals(searchMap.get("id")))
                wapper.eq("id", searchMap.get("id"));
            if(searchMap.get("name") != null && !"".equals(searchMap.get("name")))
                wapper.like("name", searchMap.get("name"));

            if(searchMap.get("caption") != null && !"".equals(searchMap.get("caption")))
                wapper.like("caption", searchMap.get("caption"));
            if(searchMap.get("brandId") != null && !"".equals(searchMap.get("brandId")))
                wapper.like("brand_id", searchMap.get("brandId"));

            if(searchMap.get("category1Id") != null && !"".equals(searchMap.get("category1Id")))
                wapper.eq("category1_id", searchMap.get("category1Id"));
            if(searchMap.get("category2Id") != null && !"".equals(searchMap.get("category2Id")))
                wapper.eq("category2_id", searchMap.get("category2Id"));

            if(searchMap.get("category3Id") != null && !"".equals(searchMap.get("category3Id")))
                wapper.eq("category3_id", searchMap.get("category3Id"));
            if(searchMap.get("templateId") != null && !"".equals(searchMap.get("templateId")))
                wapper.eq("template_id", searchMap.get("templateId"));

            if(searchMap.get("freightId") != null && !"".equals(searchMap.get("freightId")))
                wapper.eq("freight_id", searchMap.get("freightId"));
            if(searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems")))
                wapper.like("spec_items", searchMap.get("specItems"));

            if(searchMap.get("saleNum") != null && !"".equals(searchMap.get("saleNum")))
                wapper.eq("sale_num", searchMap.get("saleNum"));
            if(searchMap.get("commentNum") != null && !"".equals(searchMap.get("commentNum")))
                wapper.eq("comment_num", searchMap.get("commentNum"));

            if(searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable")))
                wapper.eq("is_marketable", searchMap.get("isMarketable"));
            if(searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec")))
                wapper.eq("is_enable_spec", searchMap.get("isEnableSpec"));

            if(searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete")))
                wapper.eq("is_delete", searchMap.get("isDelete"));
            if(searchMap.get("status") != null && !"".equals(searchMap.get("status")))
                wapper.eq("status", searchMap.get("status"));
        }
        return wapper;
    }

    /**
     * 分页查询的方法
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<TbSpu> findPage(Map<String, Object> searchMap, int page, int size) {
        Page<TbSpu> pageTbSpu = new Page<TbSpu>(page, size);
        QueryWrapper<TbSpu> query = queryWrapper(searchMap);
        query.eq("is_delete",0);// 查询没有被删除的商品
        query.eq("is_marketable",1);//查询已经上架的商品
        //query.eq("status",1);//查询出已经通过审核的商品
        IPage<TbSpu> list = this.tbSpuService.page(pageTbSpu, query);
        return pageTbSpu;
    }

    @Override
    public List<TbSpu> findList(Map<String, Object> searchMap) {
        QueryWrapper<TbSpu> wrapper = queryWrapper(searchMap);
        List<TbSpu> list = this.tbSpuService.list(wrapper);
        return list;
    }

    // 保存商品
    @Override
    @Transactional
    public void saveGoods(Goods goods) {
        TbSpu tbSpu = goods.getTbSpu();
        System.out.println(idWorker.nextId());

        tbSpu.setId(idWorker.nextId() + "");
        // 保存一个spu的信息
        int insert = spuMapper.insert(tbSpu);
        System.out.println(insert);

        //保存sku列表的信息
        TbCategory tbCategory = categoryMapper.selectById(tbSpu.getCategory3Id());
        //获取对应的品牌对象
        TbBrand tbBrand = brandMapper.selectById(tbSpu.getBrandId());
        Date date = new Date();
        List<TbSku> skuList = goods.getSkuList();
        for (TbSku sku : skuList) {
            sku.setId(idWorker.nextId() + "");

            //sku名称 =spu名称 规格值列表
            String name = tbSpu.getName();
            Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for (String value : specMap.values()) {
                name += " " + value;
            }
            sku.setName(name);
            sku.setSpuId(tbSpu.getId());
            sku.setCreateTime(date); //创建日期
            sku.setUpdateTime(date); //更新日期
            sku.setCategoryId(tbSpu.getCategory3Id());//分类id
            sku.setCategoryName(tbCategory.getName());//分类名称
            sku.setBrandName(tbBrand.getName());
            sku.setCommentNum(0);//评论数
            sku.setSaleNum(0);//销售数量

            skuMapper.insert(sku);
            skuService.savePriceToRedisById(sku.getId(),sku.getPrice());
            QueryWrapper<TbCategoryBrand> wrapper = new QueryWrapper<>();
            wrapper.eq("category_id", tbSpu.getCategory3Id());
            wrapper.eq("brand_id", tbSpu.getBrandId());
            TbCategoryBrand categoryBrand = new TbCategoryBrand();
            categoryBrand.setCategoryId(tbSpu.getCategory3Id());
            categoryBrand.setBrandId(tbSpu.getBrandId());
            int count = categoryBrandMapper.selectCount(wrapper);
            if (count == 0)
                categoryBrandMapper.insert(categoryBrand);
        }
    }

    /**
     * 修改商品之前的查询
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {
        //查询spu的列表
        TbSpu spu = baseMapper.selectById(id);

        //查询sku的列表
        QueryWrapper<TbSku> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",id);
        List<TbSku> list = skuService.list(wrapper);
        //封装组合为实体类Goods
        Goods goods = new Goods();
        goods.setTbSpu(spu);
        goods.setSkuList(list);
        return goods;
    }

    /**
     * 商品审核
     * @param id
     * @param status
     */
    @Transactional
    @Override
    public void audit(String id, String status) {
        //修改状态 审核状态和上架状态
        TbSpu spu = new TbSpu();
        spu.setId(id);
        spu.setStatus(status);
        if ("1".equals(status)){//审核通过
            spu.setIsMarketable("1");//自动上架
        }
        tbSpuService.updateById(spu);
    }

    /**
     * 商品下架
     * @param id
     */
    @Override
    public void pull(String id) {
        TbSpu spu = new TbSpu();
        spu.setId(id);
        spu.setIsMarketable("0");
        tbSpuService.updateById(spu);

        TbSpu tbSpu = tbSpuService.getById(id);
        rabbitTemplate.convertAndSend("exchange.xj","","11");
        //记录商品日志

    }

    /**
     * 商品上架
     * @param id
     */
    @Override
    public void put(String id) {
        //修改状态
        TbSpu spu = tbSpuService.getById(id);
        if (!"1".equals(spu.getStatus())){
            throw new RuntimeException("此商品未通过审核");
        }
        spu.setIsMarketable("1");
        tbSpuService.updateById(spu);

        rabbitTemplate.convertAndSend("exchange.sj","",id);
        //记录商品日志
    }

    /**
     * 批量上架
     * @param ids
     * @return
     */
    @Override
    public int putMany(String[] ids) {

        //修改状态
        TbSpu spu = new TbSpu();
        spu.setIsMarketable("1");
        QueryWrapper<TbSpu> wrapper= new QueryWrapper<>();
        wrapper.in("id", Arrays.asList(ids));
        wrapper.eq("is_marketable","0");//没有上架的
        wrapper.eq("status","1");//审核通过的
        int i = baseMapper.update(spu, wrapper);

        //添加商品日志
        return i;
    }

    //批量下架的方法
    @Override
    public int pullMany(String[] ids) {

        //修改状态为0
        TbSpu spu = new TbSpu();
        spu.setIsMarketable("0");
        QueryWrapper<TbSpu> wrapper= new QueryWrapper<>();
        wrapper.in("id", Arrays.asList(ids));
        wrapper.eq("is_marketable","1");//上架的
        wrapper.eq("status","0");//将审核状态变为未通过
        int i = baseMapper.update(spu, wrapper);

        //添加商品日志


        return i;
    }

    //商品回收站的显示查询
    @Override
    public List<TbSpu> backStation(String id) {
        QueryWrapper<TbSpu> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",id);
        List<TbSpu> list = this.tbSpuService.list(wrapper);
        if (list!=null){
            return list;
        }
        return null;
    }

    //还原商品
    @Override
    public Boolean backGoods(String id) {
        //根据id查找对象
        TbSpu spu = this.tbSpuService.getById(id);
        //将删除状态变成0(还原商品)
        spu.setIsDelete("0");
        boolean flag = tbSpuService.updateById(spu);
        if (flag){
            return true;
        }
        return false;
    }

    @Override
    public Boolean ljdelete(String id) {
        //根据id查找对象
        TbSpu spu= this.tbSpuService.getById(id);
        //根据spu的spuId找到对应的sku的数据
        QueryWrapper<TbSku> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spu.getId());
        TbSku sku = this.skuService.getOne(wrapper);
        //将状态变成3
        sku.setStatus("3");
        //将删除状态变成1
        spu.setIsDelete("1");
        //删除缓存中的价格
        Map map=new HashMap();
        map.put("spuId",id);
        List<TbSku> skuList = skuService.findList(map);
        for(TbSku sku2:skuList){
            skuService.deletePriceFromRedis(sku2.getId());
        }
        boolean flag = tbSpuService.updateById(spu);

        boolean b = skuService.updateById(sku);
        if (flag && b){
            return true;
        }
        return false;
    }

    /**
     * 分页带条件查询未审核的数据
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<TbSpu> findPageSaudit(Map<String, Object> searchMap, int page, int size) {
        Page<TbSpu> pageTbSpu = new Page<TbSpu>(page, size);
        QueryWrapper<TbSpu> query = queryWrapper(searchMap);
        query.eq("is_delete","0");
        query.eq("is_marketable","0");
        query.eq("status","0");
        IPage<TbSpu> list = this.tbSpuService.page(pageTbSpu, query);
        return pageTbSpu;
    }

    @Override
    public Page<TbSpu> findBackPage(Map<String, Object> searchMap, Integer page, Integer size) {
        Page<TbSpu> pageTbSpu = new Page<TbSpu>(page, size);
        QueryWrapper<TbSpu> query = queryWrapper(searchMap);
        query.eq("is_delete","1");//查询已经被回收的产品
        IPage<TbSpu> list = this.tbSpuService.page(pageTbSpu, query);
        return pageTbSpu;
    }
}
